package cn.skyclass.controls
{
	import flash.events.Event;
	
	import mx.controls.VScrollBar;
	import mx.core.Container;
	import mx.core.ScrollControlBase;
	import mx.core.UIComponent;
	import mx.core.mx_internal;
	import mx.events.FlexEvent;
	import mx.events.ScrollEvent;
	
	use namespace mx_internal;
	
	[Bindable]
	public class VSimpleScrollBar extends VScrollBar
	{
		public function VSimpleScrollBar()
		{
			this.addEventListener(ScrollEvent.SCROLL, onScroll);
		}

		// automatic detect and change self visibility by scroll position of registered control
		public var automaticVisible:Boolean = true;
		
		// this control is a ScrollControlBase or Container
		protected var registeredControl:UIComponent;
		
		public function registerControl(control:Object):void{
			// clear previous control
			if(registeredControl){
				registeredControl.removeEventListener(FlexEvent.UPDATE_COMPLETE, onUpdateComplete);
				registeredControl = null;
			}
			
			if(control is Container){
				var c:Container = control as Container;
				c.addEventListener(FlexEvent.UPDATE_COMPLETE, onUpdateComplete);
				registeredControl = c;
				onUpdateComplete(null);
			}else if(control is ScrollControlBase){
				var scb:ScrollControlBase = control as ScrollControlBase;
				scb.addEventListener(FlexEvent.UPDATE_COMPLETE, onUpdateComplete);
				registeredControl = scb;
				onUpdateComplete(null);				
			}
		}
		
		override protected function createChildren():void{
			super.createChildren();
			
			upArrow.focusEnabled = true;
			upArrow.buttonMode = true;
			downArrow.focusEnabled = true;
			downArrow.buttonMode = true;
		}
		
		protected function onScroll(e:ScrollEvent):void{
			if(registeredControl){
				registeredControl["verticalScrollPosition"] = e.position;
			}
		}
		
		protected function onUpdateComplete(e:Event):void{
			if(registeredControl){
				this.setScrollProperties(registeredControl.height, 
					0, registeredControl["maxVerticalScrollPosition"], 0);
				this.scrollPosition = registeredControl["verticalScrollPosition"];
				
				if(this.automaticVisible){
					this.visible = registeredControl["maxVerticalScrollPosition"] > 0;
				}
			}
		}
		
	}
}